package com.dev.security.manager.controllers;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dev.security.manager.beans.App;
import com.dev.security.manager.service.IAppService;
import com.dev.security.util.DataGrid;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 应用管理
 * @author 潜行的青衣
 * @see
 */
@Controller
@RequestMapping("/manager/app/")
public class AppController {
	
	private static final Logger LOG = LogManager.getLogger(AppController.class);
	
	@Resource
	private ObjectMapper objectMapper;
	
	@Resource
	private IAppService appService;
	
	@RequestMapping("init")
	public @ResponseBody Map<String, Integer> init(HttpSession session) {
		String file = session.getServletContext().getRealPath("/WEB-INF/");
		File dir = new File(file);
		Map<String, Integer> result = new LinkedHashMap<String, Integer>();
		int count = 0;
		try {
			File[] files = dir.listFiles(new FilenameFilter() {

				@Override
				public boolean accept(File dir, String name) {
					return name.endsWith(".json");
				}
				
			});
			
			if(files != null) {
				List<App> list = null;
				for(File t_file:files) {
					list = this.objectMapper.readValue(t_file, new TypeReference<List<App>>() {});
					this.appService.save(list);
					count += list.size();
				}
			}
		} catch (FileNotFoundException e) {
			LOG.error(e);
		} catch (IOException e) {
			LOG.error(e);
		} 
		result.put("count", count);
		return result;
	}
	
	@RequestMapping("browse")
	public @ResponseBody DataGrid<App> browse(App app, int page, int rows) {
		Sort sort = new Sort(new Order(Direction.ASC, "index"));
		return new DataGrid<App>(this.appService.findPage(app, page, rows, sort));
	}
	
	

}
